package cn.open.feishu.alert.log;

import cn.open.feishu.alert.context.SpringContext;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @Description 日志动态代理类
 * @Author fandy.lin
 * @Date 2021/11/17 1:49 下午
 **/
@Data
@Slf4j
public class LoggerProxy implements InvocationHandler {
    private Logger logger;

    public LoggerProxy(Class<?> clazz) {
        logger = LoggerFactory.getLogger(clazz);
    }

    public static Logger getLogger(Class<?> clazz) {
        LoggerProxy proxy = new LoggerProxy(clazz);
        return (Logger) Proxy.newProxyInstance(proxy.getClass().getClassLoader(), proxy.logger.getClass().getInterfaces(), proxy);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Object invoke = method.invoke(logger, args);
        try {
            LoggerHandler loggerHandler = SpringContext.getBean(LoggerHandler.class);
            loggerHandler.handleLog(method,args);
        }catch (Exception e){
            log.error("feishu alert:error 日志消息告警异常!", e);
        }
        return invoke;
    }
}
